package com.iot.manage.biz.controller;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

import java.util.List;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.*;

import com.iot.common.core.exception.ModelException;
import com.iot.common.core.util.R;
import com.iot.common.core.util.UuidUtil;
import com.iot.common.security.annotation.SecurityAuthorization;
import com.iot.manage.api.domain.SysMenu;
import com.iot.manage.api.domain.SysRole;
import com.iot.manage.api.domain.SysRoleMenu;
import com.iot.manage.api.domain.SysUser;
import com.iot.manage.api.domain.SysUserOrg;
import com.iot.manage.api.domain.SysUserRole;
import com.iot.manage.biz.service.SysRoleService;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

@RestController
@RequiredArgsConstructor
@RequestMapping("/role")
@Api(value = "role", tags = "角色管理模块")
public class RoleController {

	@Setter
	private Throwable cause;
	
	private final SysRoleService roleService;
	

	@SecurityAuthorization
	@GetMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<Page<SysRole>> list(@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {

		String sqlExceptSelect = " FROM " + SysRole.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keywords + "%' OR   O.CODE LIKE '%" + keywords + "%' ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.UPDATETIME desc ";
		return R.ok(SysRole.dao.paginate(cur, limit, "select * ", sqlExceptSelect));
	}

	@SecurityAuthorization
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<SysRole> save(@Valid SysRole sysRole) {
		if (sysRole == null) {
			throw new ModelException("角色对象不可以为空！");
		}
		if (StrKit.isBlank(sysRole.getId())) {
			sysRole.setId(UuidUtil.getUUID());
			if (sysRole.save()) {
				return R.ok();
			}
		} else {
			if (sysRole.update()) {
				return R.ok();
			}
		}
		return R.failed();
	}

	@SecurityAuthorization
	@PostMapping(value = { "/deleteById" }, produces = "application/json; charset=utf-8")
	public R<Boolean> deleteById(@RequestParam(name = "id", required = true) String id) throws Exception {
		if (SysRole.dao.deleteById(id)) {
			return R.ok(true);
		} else {
			return R.failed(false);
		}
	}

	@SecurityAuthorization
	@GetMapping(value = { "/getRoleUsers" }, produces = "application/json; charset=utf-8")
	public R<Page<SysUser>> getRoleUsers(
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "orgId", required = false, defaultValue = "") String orgId,
			@RequestParam(name = "roleId", required = false, defaultValue = "") String roleId,
			@RequestParam(name = "status", required = false, defaultValue = "") String status,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {

		String sqlExceptSelect = " FROM " + SysUser.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keywords + "%' OR   O.USERNAME LIKE '%" + keywords + "%' ) ";
		}
		if (!StrKit.isBlank(orgId)) {
			sqlExceptSelect += " AND O.ID IN ( SELECT USERID FROM " + SysUserOrg.TABLE_NAME + " WHERE ORGID='" + orgId
					+ "' ) ";
		}
		if (!StrKit.isBlank(roleId)) {
			String[] ids = roleId.split(",");
			StringBuilder sb = new StringBuilder();
			for (String id : ids) {
				if (!StrKit.isBlank(id)) {
					sb.append("'").append(id).append("'").append(",");
				}
			}
			if (StrKit.equals(status, "0"))
				sqlExceptSelect += " AND O.ID NOT IN ( SELECT USER_ID FROM " + SysUserRole.TABLE_NAME
						+ " WHERE ROLE_ID in (" + sb.substring(0, sb.length() - 1) + ")) ";
			else if (StrKit.equals(status, "1")) {
				sqlExceptSelect += " AND O.ID IN ( SELECT USER_ID FROM " + SysUserRole.TABLE_NAME
						+ " WHERE ROLE_ID in (" + sb.substring(0, sb.length() - 1) + ")) ";
			}
		}
		sqlExceptSelect += "  ORDER BY   O.UPDATE_TIME desc ";
		return R.ok(SysUser.dao.paginate(cur, limit, "select * ", sqlExceptSelect));
	}

	@SecurityAuthorization
	@PostMapping(value = { "/saveRoleUsers" }, produces = "application/json; charset=utf-8")
	public R<Boolean> saveRoleUsers(@RequestParam(name = "roleIds", required = true) String roleIds,
			@RequestParam(name = "userIds", required = true) String userIds,
			@RequestParam(name = "status", required = true) String status) throws Exception {
		String[] ids = userIds.split(",");
		StringBuilder sb = new StringBuilder();
		for (String id : ids) {
			if (!StrKit.isBlank(id) && !StrKit.equals("1", id)) {
				sb.append("'").append(id).append("'").append(",");
			}
		}

		String[] rids = roleIds.split(",");
		StringBuilder rsb = new StringBuilder();
		for (String id : rids) {
			if (!StrKit.isBlank(id)) {
				rsb.append("'").append(id).append("'").append(",");
			}
		}
		if (StrKit.isBlank(sb.toString()) || StrKit.isBlank(rids.toString())) {
			return R.failed("参数必填！");
		}
		if (StrKit.equals("0", status)) {
			SysUserRole sysUserRole;
			for (String roleId : rids) {
				if (!StrKit.isBlank(roleId)) {
					for (String userId : ids) {
						if (!StrKit.isBlank(userId)) {
							sysUserRole = new SysUserRole();
							sysUserRole.setUserId(userId);
							sysUserRole.setRoleId(roleId);
							if (!sysUserRole.save()) {
								throw new Exception("分配角色用户失败！");
							}
						}
					}
				}
			}
			return R.ok();
		} else {
			int i = Db.delete(
					"delete from " + SysUserRole.TABLE_NAME + " where  role_id in (" + rsb.substring(0, rsb.length() - 1)
							+ ") and user_id in (" + sb.substring(0, sb.length() - 1) + ") ");
			if (i > 0) {
				return R.ok();
			} else {
				return R.failed();
			}
		}
	}
	
	
	@SecurityAuthorization
	@RequestMapping(value = "/getRoleMenuTree", method = RequestMethod.GET)
	public R<List<SysMenu>> getRoleMenuTree(@RequestParam(name = "roleId", required = false) String roleId) {
		return R.ok(roleService.getRoleMenuTree(roleId));
	}
	
	
	@SecurityAuthorization
	@PostMapping(value = { "/saveRoleMenus" }, produces = "application/json; charset=utf-8")
	public R<Boolean> saveRoleMenus(@RequestParam(name = "menuIds", required = false) String menuIds,@RequestParam(name = "roleId", required = true) String roleId) throws Exception {
		SysRoleMenu sysRoleMenu;
		String[] ids = menuIds.split(",");
		StringBuffer sb=new StringBuffer();
		for (String menuId : ids) {
			if (!StrKit.isBlank(menuId)) {
				sysRoleMenu=SysRoleMenu.dao.findByIds(roleId,menuId);
				if(sysRoleMenu==null) {
					sysRoleMenu =new SysRoleMenu();
					sysRoleMenu.setMenuId(menuId);
					sysRoleMenu.setRoleId(roleId);
					if(!sysRoleMenu.save()) {
						throw new Exception("保存角色操作权限失败！");
					}
				}
				sb.append("'").append(menuId).append("'").append(",");
			}
		}
		if(!StrKit.isBlank(sb.toString())) {
			Db.delete("delete from "+SysRoleMenu.TABLE_NAME+" where menu_id not in ("+sb.substring(0, sb.length()-1)+") and role_id=? ",roleId);
			return R.ok("用户授权权限成功！",true);
		}else {
			int i=Db.delete("delete from "+SysRoleMenu.TABLE_NAME+" where role_id=? ",roleId);
			if(i>0) {
				return R.ok("用户操作权限已经取消！",true);
			}else {
				return R.warn("未变更权限！",false);
			}
		}
		
	}

}
